﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Topro.Application.Impl
{
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Query;
    using Topro.Entity.Response.Warehouse;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 仓库业务接口实现
    /// </summary>
    public class WarehouseServiceImpl: WarehouseService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public WarehouseServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取仓库
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public WarehouseResponse Get(int id)
        {
            var warehouse = _db.DbConnection.QueryFirst<WarehouseResponse>("select Id,Name,Code,Status,CreatedBy,CreatedTime from t_warehouse where Id=@Id", new { Id = id });
            if (warehouse != null)
            {
                return warehouse;
            }

            return null;
        }

        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public List<WarehouseResponse> GetListByStatus(int status)
        {
            return _db.DbConnection.Query<WarehouseResponse>("select Id,Name,Code,Status,CreatedBy,CreatedTime from t_warehouse where Status=@Status", new { Status = status }).ToList();
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var warehouse = Get(id);
                if (warehouse == null)
                {
                    throw new Exception("仓库记录不存在.");
                }

                var updateSql = "UPDATE t_warehouse SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 仓库查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<WarehouseQueryResponse> GetPager(WarehouseQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Name,Code,Status,CreatedBy,CreatedTime";
            var tableName = "t_warehouse";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";


            var sb = new StringBuilder();

            sb.AppendFormat("select count(1) from {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);

            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var total = multi.ReadFirst<int>();

                var list = multi.Read<WarehouseQueryResponse>();

                return new DataGrid<WarehouseQueryResponse>()
                {
                    Rows = list,
                    Total = total
                };
            }
        }
    }
}
